package com.cinyi.ormx.android;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.os.Build;
import android.os.Handler;

import com.cinyi.ormx.android.context.LogHelper;
import com.cinyi.ormx.android.context.OrmxContext;
import com.cinyi.ormx.android.dao.DefaultSQLiteHelper;
import com.cinyi.ormx.android.db.DbHelper;

public class App extends OrmxContext {
	public static final String TAG = "App" ;
	
	@SuppressWarnings("deprecation")
	public static final int SDK_INT = Integer.valueOf(Build.VERSION.SDK);
	
	public static final String TRUST_STORE_PATH = null;

	/**
	 * Thread to execute tasks in background..
	 */
	private final ExecutorService backgroundExecutor;

	private Handler appHandler;

	private static Activity lastActivity = null ;

	private DbHelper mSQLiteHelper ;
	
	private static App instance;

	public static App getInstance(){
		if (instance == null)
			throw new IllegalStateException();
		return instance;
	}
	
	public App() {
		instance = this;
		backgroundExecutor = Executors.newSingleThreadExecutor();
	}

	@Override
	public void onCreate() {
		super.onCreate();
//		alarmManager =(AlarmManager)getSystemService(ALARM_SERVICE);
		
		appHandler = new Handler();
		mSQLiteHelper = new DbHelper(this);
		
	}

	/**
	 * @TODO 通过设置，在低内存时候的一些处理
	 */
	@Override
	public void onLowMemory() {
		super.onLowMemory();
		LogHelper.d(TAG, "onLowMemory");
	}

	@Override
	public void onTerminate() {
		LogHelper.d(TAG, "onTerminate");
		backgroundExecutor.shutdown();
		super.onTerminate();
	}

	public void onServiceStarted(){
		runInBackground(new Runnable() {
			@Override
			public void run() {
			}
		});
	}
	
	public static void setLastActivity(Activity act){
		lastActivity = act ;
	}
	
	public static Activity getLastActivity(){
		return lastActivity;
	}

	/**
	 * Notify about error.
	 * 
	 * @param resourceId
	 */
	public void onError(final int resourceId) {
		LogHelper.d(TAG, "onError");
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
			}
		});
	}

	/**
	 * Submits request to be executed in background.
	 * 
	 * @param runnable
	 */
	public void runInBackground(final Runnable runnable) {
		backgroundExecutor.submit(new Runnable() {
			@Override
			public void run() {
				try {
					runnable.run();
				} catch (Exception e) {
				}
			}
		});
	}

	/**
	 * Submits request to be executed in UI thread.
	 * 
	 * @param runnable
	 */
	public void runOnUiThread(final Runnable runnable) {
		appHandler.post(runnable);
	}

	/**
	 * Submits request to be executed in UI thread.
	 * 
	 * @param runnable
	 * @param delayMillis
	 */
	public void runOnUiThreadDelay(final Runnable runnable, long delayMillis) {
		appHandler.postDelayed(runnable, delayMillis);
	}

	public void addManager(Object instance) {
	}

	@Override
	public DefaultSQLiteHelper getSQLiteHelper() {
		return mSQLiteHelper;
	}

}

